package com.orangelife.webservice.service.bill.impl;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.Response;

import com.orangelife.redis.core.redis.session.redisSession.WebServiceSession;
import com.orangelife.setting.constant.CodeConst;
import com.orangelife.setting.constant.InfoConst;
import com.orangelife.webservice.base.PageUtils;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.orangelife.common.AbstractV2TransferService;
import com.orangelife.exception.AppBizException;
import com.orangelife.service.bill.IBillService;
import com.orangelife.service.bill.IComputeBillService;
import com.orangelife.service.bill.impl.BillService;
import com.orangelife.service.offset.IOffsetService;
import com.orangelife.service.propFeeAccount.IPropFeeAccountService;
import com.orangelife.service.propFeeCommInfo.IPropFeeCommInfoService;
import com.orangelife.service.propFeeComputeRule.model.Rule;
import com.orangelife.service.property.PropCollectionService;
import com.orangelife.utils.DateUtil;
import com.orangelife.utils.IdUtil;
import com.orangelife.utils.StringUtils;
import com.orangelife.webservice.service.bill.IBillWebService;
import com.orangelife.webservice.service.bill.entity.BillDto;

@Service("billWebService")
public class BillWebService extends AbstractV2TransferService implements
		IBillWebService {

	@Resource(name = "billService")
	private IBillService billService;
	@Resource(name = "propCollectionService")
	private PropCollectionService propCollectionService;
	@Resource(name = "computeBillService")
	private IComputeBillService computeBillService;
	@Resource(name = "propFeeCommInfoService")
	private IPropFeeCommInfoService propFeeCommInfoService;

	@Resource(name = "offsetService")
	private IOffsetService offsetService;
	@Resource(name = "propFeeAccountService")
	private IPropFeeAccountService propFeeAccountService;


	@Override
	public Response addinfo(HttpServletRequest servletRequest,
			final BillDto billDto) throws Exception {

		if (StringUtils.isBlank(billDto.getCommID())) {

			return this.abnormalResp(100002, "小区信息不能为空");

		}

		if (BillService.getFeeStatus(billDto.getCommID())) {

			return this.normalResp(100001, "账单正在生成中，请稍后再试");

		}

		List<Map<String, Object>> mm = billService.checkMeter(
				billDto.getCommID(), billDto.getStartTime());

		if (mm != null && mm.size() > 0) {

			Map<String, Object> m = new HashMap<String, Object>();
			m.put("list", mm);

			return this.normalResp(10000, "数据不完整", m);

		}

		if (!BillService.setFeeStatusLock(billDto.getCommID())) {

			return this.normalResp(100001, "账单正在生成中，请稍后再试");

		}

		String planid = IdUtil.getuuId();

		Map<String, Object> planmap = new HashMap<String, Object>();
		planmap.put("planID", planid);
		planmap.put("commID", billDto.getCommID());
		planmap.put("planName", "生成缴费账单");
		planmap.put("planContent", "生成缴费账单");
		planmap.put("planType", "1");
		planmap.put("planStatus", "2");

		planmap.put("remark", "");

		planmap.put("itemTtat", "1");

		billService.crePlan(planmap);
		billDto.setPlanID(planid);

		new Thread() {
			public void run() {

				String plan_status = "3";
				try {
					billService.startCreFeeDetail(billDto);

					return;
				} catch (Exception e) {

					e.printStackTrace();
					plan_status = "4";

				} finally {
					BillService.setFeeStatusUnlock(billDto.getCommID());
					Map<String, Object> planmap1 = new HashMap<String, Object>();
					planmap1.put("planid", billDto.getPlanID());
					planmap1.put("plan_status", plan_status);
					planmap1.put("remark", billDto.getStartTime());

					planmap1.put("finishTime", new Date());

					try {

						if (plan_status.equals("3")) {

							billService.updateMerRecordStatus(
									billDto.getCommID(), "2", "3", null);
							billService.updateMerRecordStatus(
									billDto.getCommID(), "1", "2", null);
							billService.updateMerRecordStatus(
									billDto.getCommID(), "0", "1", null);

						}

						billService.updatePlan(planmap1);

					} catch (AppBizException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}

			}

		}.start();

		// for (String s : billDto.getFeeTypeIDs()) {
		//
		// billService.creFeeDetail(billDto.getCommID(),billDto.getBuildingID(),billDto.getUnitID(),billDto.getApartmentID(),s
		// , billDto.getStartTime(), billDto.getEndTime());
		//
		// }
		// TODO Auto-generated method stub
		return this.normalResp();
	}

	public static void main(String[] args) {

		try {

			Long l = Long.parseLong("ssss");
		} catch (Exception e) {

			e.printStackTrace();
		}

	}

	@Override
	public Response pastFeedetail(HttpServletRequest servletRequest,
			String commID) throws Exception {
		//
		// Map<String,Object> param=new HashMap<String,Object>();
		// param.put("commID", commID);
		// param.put("code", "curDate");
		// List<Map<String,Object>>
		// p=propFeeCommInfoService.bauthfindPropFeeCommInfoByMap(param);
		//
		// if(p==null||p.size()==0||p.size()>1){
		//
		// return this.normalResp();
		//
		// }
		// Map<String, Object> res=p.get(0);
		// Map<String, Object> m = new HashMap<String, Object>();
		// m.put("lastTime", res.get("val"));
		// m.put("nestTime", DateUtil.getNextQuarter(
		// res.get("val").toString()));

		Map<String, Map<String, Object>> config = propFeeCommInfoService
				.findPropFeeCommInfo(commID);

		if (config == null
				|| config.get("curDate") == null
				|| StringUtils.isBlank(config.get("curDate").get("val")
						.toString())
				|| config.get("period") == null
				|| StringUtils.isBlank(config.get("period").get("val")
						.toString())) {

			// BillService.setFeeStatusUnlock(commID);
			return this.normalResp(100001, "初始账单生成时间未配置");

		}
		String startTime = config.get("curDate").get("val").toString();

		String fixTime = "";

		if (config.get("fixeddate") != null) {
			fixTime = config.get("fixeddate").get("val").toString();
		}

		String endTime = "";
		if ("1".equals(config.get("period").get("val").toString())) {

			endTime = DateUtil.addMonth(startTime, 1);

		} else if ("2".equals(config.get("period").get("val").toString())) {

			endTime = DateUtil.getNextQuarter(startTime);

		}
		Map<String, Object> m = new HashMap<String, Object>();
		m.put("lastTime", startTime);
		m.put("fixTime", fixTime);
		m.put("nextTime", endTime);
		m.put("restMoney", config.get("restMoney").get("val"));
		m.put("reliefMoney", config.get("reliefMoney").get("val"));
		m.put("realPay", config.get("realPay").get("val"));

		m.put("period", config.get("period").get("val"));
		return this.normalResp(m);

	}

	@Override
	public Response lastFinishPlan(HttpServletRequest servletRequest,
			Map<String, Object> map) throws Exception {
		Date d = null;

		if (map != null && !"0".equals(map.get("time").toString())) {

			d = new Date((long) map.get("time"));
		}

		List<String> l = (List<String>) map.get("commIDs");
		List<Map<String, Object>> mmm = billService.getLastFinishPlans(l, d);

		// TODO Auto-generated method stub
		return normalResp2(1, 10, 1l, mmm);
	}



	@Override
	public Response cancelPlan(HttpServletRequest servletRequest, String planID)
			throws Exception {

		if (planID == null) {

			return this.abnormalResp(100001, "planID不能为空");

		}

		List<Map<String, Object>> mmm = billService.checkPlan(planID);

		if (mmm != null && mmm.size() > 0) {

			return this.abnormalResp(100002, "改计划生成的账单已产生缴费费用，不能撤销");
		}

		Map<String, Object> res = billService.getPlanDetail(planID);

		if (res == null) {

			return this.abnormalResp(100001, "计划不存在");

		}

		if (!"3".equals(StringUtils.toString(res.get("plan_status")))) {

			return this.abnormalResp(100001, "计划非正常状态请刷新页面，查看是否已被撤销");

		}

		billService.canclePlan(planID);

		// TODO Auto-generated method stub
		return this.normalResp();
	}

	@Override
	public Response getprintplan2(HttpServletRequest servletRequest,
			String commID, String planType, String pageIndex, String pageSize)
			throws Exception {

		// TODO Auto-generated method stub
		if (StringUtils.isBlank(commID)) {
			return this.abnormalResp(99, "小区号不能为空！");
		}

		List<Map<String, Object>> list = billService.getprintplan(commID,
				planType, pageIndex, pageSize);
		Long total = ((Page<Map<String, Object>>) list).getTotal();
		// TODO Auto-generated method stub
		return this.normalResp(Integer.valueOf(pageIndex),
				Integer.valueOf(pageSize), total, list);

	}

	@Override
	public Response _computeFeeDetail(HttpServletRequest servletRequest,
			final BillDto billDto) throws Exception {
		Map<String, Object> res = null;
		try {
			if (StringUtils.isBlank(billDto.getCommID())) {

				return this.abnormalResp(100002, "小区信息不能为空");

			}

			// if (BillService.getFeeStatus(billDto.getCommID())) {
			//
			// return this.normalResp(100001, "账单正在生成中，请稍后再试");
			//
			// }

			if (!BillService.setFeeStatusLock(billDto.getCommID())) {

				return this.normalResp(100001, "账单正在生成中，请稍后再试");

			}

			/***
			 * 获计算配置的
			 */
			Map<String, Map<String, Object>> config = propFeeCommInfoService
					.findPropFeeCommInfo(billDto.getCommID());

			if (config == null
					|| config.get("curDate") == null
					|| StringUtils.isBlank(config.get("curDate").get("val")
							.toString())
					|| config.get("period") == null
					|| StringUtils.isBlank(config.get("period").get("val")
							.toString())) {

				BillService.setFeeStatusUnlock(billDto.getCommID());
				return this.normalResp(100001, "初始账单生成时间未配置");

			}

			/***
			 * 获取计算 时间
			 */
			String startTime = config.get("curDate").get("val").toString();

			/***
			 * 获取按月份
			 */
			if ("1".equals(config.get("period").get("val").toString())) {

				billDto.setStartTime(DateUtil.addMonth(startTime, 1));
				billDto.setEndTime(DateUtil.addMonth(startTime, 1));

				/***
				 * 安季度计算
				 */
			} else if ("2".equals(config.get("period").get("val").toString())) {

				billDto.setStartTime(DateUtil.addMonth(startTime, 1));
				billDto.setEndTime(DateUtil.getNextQuarter(startTime));

			}

			/***
			 * 获取每个小区的表记录是否完整
			 */

			List<Map<String, Object>> mm = billService.checkMeter(
					billDto.getCommID(), billDto.getEndTime());

			if (mm != null && mm.size() > 0) {

				Map<String, Object> m = new HashMap<String, Object>();
				m.put("list", mm);
				BillService.setFeeStatusUnlock(billDto.getCommID());
				return this.normalResp(10000, "数据不完整", m);

			}

			/***
			 * 获取每个小区的计算规则
			 */
			res = computeBillService.checkRules(billDto);

			if (res == null || !"0".equals(res.get("errCode").toString())) {

				BillService.setFeeStatusUnlock(billDto.getCommID());
				return this
						.abnormalResp(1000001, res.get("errInfo").toString());

			}
			String planid = IdUtil.getuuId();

			Map<String, Object> planmap = new HashMap<String, Object>();

			planmap.put("planID", planid);
			planmap.put("commID", billDto.getCommID());
			planmap.put("planName", "生成缴费账单");
			planmap.put("planContent", "生成缴费账单");
			planmap.put("planType", "1");

			// 记录该次生成时的上次生成时间，和当前生成时间
			planmap.put("lastDate", startTime);
			planmap.put("curDate", billDto.getEndTime());
			planmap.put("planStatus", "2");
			planmap.put("remark", "");

			planmap.put("itemTtat", "1");

			/**
			 * 开始打印计划
			 */
			billService.crePlan(planmap);
			billDto.setPlanID(planid);

		} catch (Exception e) {

			BillService.setFeeStatusUnlock(billDto.getCommID());
			e.printStackTrace();
			return this.abnormalResp(1000001, "系统异常");
		}

		final List<Rule> rules = (List<Rule>) res.get("rules");
		new Thread() {
			public void run() {

				String plan_status = "3";
				try {

					/**
					 * 开始生成缴费计划
					 */
					computeBillService.startCreFeeDetail(billDto, rules);

					return;
				} catch (Exception e) {

					e.printStackTrace();
					plan_status = "4";
				} finally {
					BillService.setFeeStatusUnlock(billDto.getCommID());
					Map<String, Object> planmap1 = new HashMap<String, Object>();
					planmap1.put("planid", billDto.getPlanID());
					planmap1.put("plan_status", plan_status);
					planmap1.put("remark", billDto.getStartTime());
					planmap1.put("finishTime", new Date());
					try {
						billService.updatePlan(planmap1);
						if (plan_status.equals("3")) {

							/***
							 * 自动冲抵生成的费用
							 */
							List<Map<String, Object>> apartList = propFeeAccountService
									.getAountInfoHasMoney(billDto.getCommID());
							for (Map<String, Object> map2 : apartList) {
								offsetService.autoOffset(billDto.getCommID(),
										map2.get("apartment_id").toString(),
										null, null);
							}
						}

					} catch (AppBizException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}

			}

		}.start();

		return this.normalResp();

	}

	@Override
	public Response _computePreFeeDetail(HttpServletRequest servletRequest,
			BillDto billDto) throws Exception {

		List<Map<String, Object>> res = computeBillService
				.preFeeDetail(billDto);
		// TODO Auto-generated method stub
		return this.normalResp(0, 1, 0l, res);
	}

	@Override
	public Response autoCrePreFee(HttpServletRequest servletRequest,
			String commID, String planType, String pageIndex, String pageSize)
			throws Exception {
		computeBillService.autoCrePreFeeDetail(commID);
		return null;
	}

	@Override
	public Response getNewPropFeeBill(HttpServletRequest servletRequest, Map<String,Object> map) throws Exception {
		String endDate=null;
		WebServiceSession session = this.getWebServiceSession(servletRequest);
		if (session == null) {
			return this.abnormalResp(CodeConst.SYS_CODE_2001,
					InfoConst.SYS_INFO_2001);
		}
		if (map == null) return this.abnormalResp(100001, "对象不能为空");
		List<String> commIDs = (List<String>) map.get("commIDs");

		endDate=session.getQueryPropbillendDate();
		if(endDate==null) {
			endDate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		}

		session.setQueryPropbillendDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		List<Map<String,Object>> res=billService.getNewPropFeeBill(commIDs,endDate);
		return this.normalResp(0, 1, 0l, res);
	}


}
